﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Vkontakte.Api
{
	public static class Serializer
	{
		#region LoadObjectXml
		#region public static T LoadObjectXml<T>( string filename )
		/// <summary>
		/// Стандартная загрузка объектов из XML-файла
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="stream"></param>
		/// <returns></returns>
		public static T LoadObjectXml<T>(Stream stream)
		{
			XmlSerializer xmlS = new XmlSerializer(typeof(T));
			XmlSerializerNamespaces xmlNs = new XmlSerializerNamespaces();
			xmlNs.Add("", "");
			T ret = (T)xmlS.Deserialize(stream);
			return ret;
		}
		#endregion
		#endregion

		public static T LoadObjectXmlString<T>(string data)
		{
			XmlSerializer xmlS = new XmlSerializer(typeof(T));
			XmlSerializerNamespaces xmlNs = new XmlSerializerNamespaces();
			xmlNs.Add("", "");
			T ret;
			using (StringReader reader = new StringReader(data))
			{
				ret = (T)xmlS.Deserialize(reader);
			}
			return ret;
		}

		#region SaveObjectXml
		/// <summary>
		/// Стандартное сохранение объектов в XML-файл
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj"></param>
		/// <param name="stream"></param>
		public static void SaveObjectXml<T>(T obj, Stream stream)
		{
			XmlSerializer xmlS = new XmlSerializer(typeof(T));
			XmlSerializerNamespaces xmlNs = new XmlSerializerNamespaces();
			xmlNs.Add("", "");
			xmlS.Serialize(stream, obj, xmlNs);
		}
		#endregion

		public static string SaveObjectXmlString<T>(T obj)
		{
			XmlSerializer xmlS = new XmlSerializer(typeof(T));
			XmlSerializerNamespaces xmlNs = new XmlSerializerNamespaces();
			xmlNs.Add("", "");
			string ret;
			using (StringWriter w=new StringWriter())
			{
				xmlS.Serialize(w, obj, xmlNs);
				ret = w.GetStringBuilder().ToString();
			}
			return ret;
		}
	}

}
